﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.IO;
using System.Collections;

namespace DocumentManager
{
    public partial class AddDocument : Form
    {
        public AddDocument()
        {
            InitializeComponent();

        }

        private void AddDocument_Load(object sender, EventArgs e)
        {
            ArrayList users = CommonFunctions.GetAllUsersFromDB();
            cbUsers.DisplayMember = "Text";
            cbUsers.ValueMember = "Value";
            cbUsers.DataSource = users;
        }

        private void btnSubmitDoc_Click(object sender, EventArgs e)
        {
            ((Form1)MdiParent).HideStatusBarMessages();
            /*
            if (txtManNumber.Text.Trim().Length == 0)
            {
                ((Form1)MdiParent).WriteErrorMessage("A Man Number is required.");
                return;
            }*/
            if (cbUsers.SelectedIndex == -1 || cbUsers.SelectedIndex == 0)
            {
                ((Form1)MdiParent).WriteErrorMessage("A User is required.");
                return;
            }
            //Validate that man number exists in users table
            /*
            if (!((Form1)MdiParent).UserExists(txtManNumber.Text.Trim()))
            {
                ((Form1)MdiParent).WriteErrorMessage("Man Number " + txtManNumber.Text + " does not exist. Please contact a Flight Chief or Systems Administrator.");
                return;
            }*/

            if (txtDescription.Text.Trim().Length == 0)
            {
                ((Form1)MdiParent).WriteErrorMessage("A Description is required.");
                return;
            }

            if (txtFile.Text.Trim().Length == 0)
            {
                ((Form1)MdiParent).WriteErrorMessage("A File is required.");
                return;
            }

           // String ManNumber = txtManNumber.Text.Trim();
            String ManNumber = cbUsers.SelectedValue.ToString();

            if (ManNumber.Length != 5)
            {
                ManNumber = ManNumber.PadLeft(5, '0');
//                txtManNumber.Text = ManNumber;
            }
            //assume datetime picker is correct, hopefully user changed it?
            String Sql = @"Insert into Documents (Description, Document, Created_Date, Man_Number, Course_Date) 
                                      values (@Description,@Document,@CreatedDate,@ManNumber,@CourseDate)";

            OleDbConnection con = new OleDbConnection(((Form1)MdiParent).ConnectionString);

            OleDbCommand com = con.CreateCommand();
            try
            {
                FileInfo fileInfo = new FileInfo(txtFile.Text);
                if (!fileInfo.Exists)
                {
                    ((Form1)MdiParent).WriteErrorMessage("File no longer exists, please select a new file.");
                    return;
                }
                byte[] fileData = null;
                // Read file data into buffer
                using (FileStream fs = fileInfo.OpenRead())
                {
                    fileData = new byte[fileInfo.Length];
                    int nReadLength = fs.Read(fileData, 0, (int)(fileInfo.Length));
                }

                com.CommandText = Sql;
                com.Parameters.AddWithValue("@Description", txtDescription.Text.Trim());
                com.Parameters.AddWithValue("@Document", fileData);
                com.Parameters.AddWithValue("@CreatedDate", DateTime.Now.ToOADate());
                int mNumber = Int16.Parse(ManNumber);
                com.Parameters.AddWithValue("@ManNumber", mNumber);
                com.Parameters.AddWithValue("CourseDate", dateTimePicker1.Value.ToOADate());

                con.Open();

                int result = com.ExecuteNonQuery();
                if (result > 0)
                {
                    ((Form1)MdiParent).WriteOtherMessage("Record successfully created for " + ManNumber + ".");
                    txtDescription.Text = String.Empty;
                    txtFile.Text = String.Empty;
                    dateTimePicker1.ResetText();
                }
                else
                {
                    MessageBox.Show("Error. Contact Application Administrator.");
                }
            }
            catch (Exception ex)
            {
                //error
                MessageBox.Show("Error. Contact Application Administrator.");
            }
            finally
            {
                con.Close();
            }
        }

        private void txtFile_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.Cancel)
            {
                return;
            }
            String filePath = openFileDialog1.FileName;
            if (filePath == "")
                return;

            if (System.IO.File.Exists(filePath) == false)
                return;
            else
                txtFile.Text = filePath;
        }


    }
}
